package com.culture.bootdemo.controller.thread;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wenjl
 * @Date: 2021/8/20 17:46
 * @Description: ThreadLocal  关于ThreadLocal是否用static 修饰 返回的是一个对象，但实例实际是不同的；但是每个线程需要new一个SimpleDateFormat对象 ，而不能写成static对象
 */
public class ThreadLocalDemo {
    public static ExecutorService threadPool = Executors.newFixedThreadPool(16);


    public static void main(String[] args) throws InterruptedException {
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                String date = new ThreadLocalDemo().date(finalI);
                System.out.println(date);
                list.add(date);
            });
        }
        //休眠3秒
        TimeUnit.SECONDS.sleep(3);
        threadPool.shutdown();
        //两个数量一致表示 没问题
        System.out.println("list个数：" + list.size());
        System.out.println("set个数：" + new HashSet<>(list).size());
    }

    public String date(int seconds) {
        Date date = new Date(1000L * seconds);
        SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
        return dateFormat.format(date);
    }
}

class ThreadSafeFormatter {

    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));

}
